package cn.lfzj.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.lfzj.model.Sequence;
import cn.lfzj.service.BusLineService;
import cn.lfzj.service.SequenceService;

@CrossOrigin
@Controller
@RequestMapping("/sequence")
public class SequenceController {
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private SequenceService sequenceService;

	/**
	 * 显示全部班次
	 */
	@RequestMapping("showAll")
	public String showSequence(Integer pageNum, Model model) {
		if (pageNum == null || pageNum <= 0) {
			pageNum = 1;
		}
		PageHelper.startPage(pageNum, 10);
		List<Sequence> list = sequenceService.findAll();
		PageInfo<Sequence> pageInfo = new PageInfo<Sequence>(list);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("sequenceList", list);
		return "manager/showSequence";
	}

	/**
	 * 显示新增页
	 */
	@RequestMapping("showAdd")
	public String showAdd(Model model) {
		model.addAttribute("busLineList", busLineService.findAll());
		return "manager/addSequence";
	}

	/**
	 * 新增班次
	 */
	@RequestMapping("add")
	@ResponseBody
	public String add(@Valid Sequence sequence, BindingResult result) {
		JSONObject json = new JSONObject();
		int code = -3;
		if (!result.hasErrors()) {
			code = sequenceService.addSequence(sequence);
		}
		json.put("code", code);
		return json.toJSONString();
	}

	/**
	 * 删除班次
	 */
	@RequestMapping("del")
	public String del(String sequenceId) {
		sequenceService.delSequence(sequenceId);
		return "forward:/sequence/showAll";
	}

	/**
	 * 显示修改页
	 */
	@RequestMapping("showUpd")
	public String showUpd(String sequenceId, Model model) {
		model.addAttribute("sequence", sequenceService.selById(sequenceId));
		model.addAttribute("busLineList", busLineService.findAll());
		return "manager/updSequence";
	}

	/**
	 * 查询未发车班次
	 */
	@RequestMapping(value = "sequJson", produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String sequJson(String date, String lineId) {
		JSONObject json = new JSONObject();
		json.put("sequ", sequenceService.findNotStart(date, lineId));
		return json.toJSONString();
	}

	/**
	 * 修改班次
	 */
	@RequestMapping("upd")
	@ResponseBody
	public String updBusLine(@Valid Sequence sequence, BindingResult result) {
		JSONObject json = new JSONObject();
		int code = -3;
		if (!result.hasErrors()) {
			code = sequenceService.updSequence(sequence);
		}
		json.put("code", code);
		return json.toJSONString();
	}

}
